<template>
  <div>
    <tablePaging :tableItem="tableItem" :operationItem="operationItem"></tablePaging>
    <!-- 缴费 -->
    <el-dialog v-model="paymentDialog.dialogVisible" title="缴费" @close="paymentDialog.close(), payInfo.payProofUrl = ''">
      <!-- 缴费表单 -->
      <el-form ref="paymentForm" :label-position="labelPosition" label-width="100px" :model="payInfo"
        :rules="paymentRules">
        <el-form-item label="缴费金额" prop="payPrice">
          <el-input @input="payInfo.payPrice = keepTwoPoint(payInfo.payPrice, 30)" maxlength="30"
            v-model="payInfo.payPrice" placeholder="请输入缴费金额" />
        </el-form-item>

        <el-form-item label="缴费日期" prop="payDate">
          <div class="block">
            <el-date-picker v-model="payInfo.payDate" type="date" placeholder="请选择缴费日期" format="YYYY/MM/DD"
              value-format="YYYY-MM-DD" />
          </div>
        </el-form-item>

        <el-form-item label="缴费凭据">
          <el-upload class="avatar-uploader" :action="uploadFileUrl" :headers="headers" :show-file-list="false" 
            :on-success="handleUploadSuccess" :on-error="handleUploadError" accept=".jpeg,.png,.jpg,.bmp">
            <img style="width: 150px; height: 150px; object-fit: scale-down;" v-if="payInfo.payProofUrl" :src="payInfo.payProofUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="paymentDialog.close">取 消</el-button>
          <el-button type="primary" @click="paymentDialog.confirm">
            确 定
          </el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import tablePaging from '@/views/common/component/table-paging'
import { onMounted, reactive, ref } from 'vue'
import { tableItem, listAllListApi, paymentApi, batchDelApi } from './const.js'
import newDialog from '@/hooks/useDialog.js';
import { Plus, Search } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { getToken } from "@/utils/auth";
import { keepTwoPoint } from "../../../../utils/checkInput.js";
const router = useRouter()

const { ctx, proxy } = getCurrentInstance();
const operationItem = reactive({
  defaultSearch: true,//默认搜索按钮
  defaultRefresh: false,//默认重置按钮
  SearchText: "查询", //搜索文字 默认搜索
  RefreshText: "重置", //刷新文字 默认重置
  customTableHeader: true,//自定义表单头部插槽
  SearchItem: [
    {
      code: "batchNum",
      name: "批次号",
      type: 'input',
    },
    {
      code: 'insId',
      name: '所属机构',
      type: 'select',
      value: 'userId',
      label: 'nickName',
      options: [
        { label: '全部', value: 1 },
      ]
    },
    {
      code: 'payFlag',
      name: '缴费状态',
      type: 'select',
      options: [
        { label: '已缴费', value: 1 },
        { label: '未缴费', value: 0 },
      ]
    },
    {
      code: 'status',
      name: '审核状态',
      type: 'select',
      options: [
        { label: '已审核', value: 2 },
        { label: '待审核', value: 1 },
      ]
    },
    {
      // 带默认的可以不写
      code: "daterange",//
      startName: "导入时间", //默认是开始时间 type为 daterange生效
      rangeName: "", //默认是至 type为 daterange生效
      endName: "导入时间", //默认是结束时间 type为 daterange生效
      valueFormat: "", //默认是YYYY-MM-DD
      placeholder: "请选择日期",//默认是请选择日期type为date生效
      type: "daterange",//daterange或date
    },
  ],
  //   v-hasPermi="['monitor:job:export']"
  menuArray: []
})

const insIdInit = () => {
  listAllListApi({ typeCodeList: ['institution','association'] }).then(res => {
    operationItem.SearchItem[1].options = res.data
  })
}
// 
const headers = ref({ Authorization: "Bearer " + getToken() });
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload"); // 上传文件服务器地址
onMounted(() => {
   insIdInit() ;
})

//点击查看，跳转路由
tableItem.btnArray[0].handle = (row) => {
  router.push({
    path: '/modules/train/examine/query', query: {
      type: 'look',
      batchNum: row.batchNum,
      studentNum: row.studentNum,
      payFlag: row.payFlag,
      id: row.id,
    }
  })
}
//点击查看，跳转路由
tableItem.btnArray[1].handle = (row) => {
  router.push({
    path: '/modules/train/examine/query', query: {
      batchNum: row.batchNum,
      studentNum: row.studentNum,
      payFlag: row.payFlag,
      id: row.id,
    }
  })
}

//审核
tableItem.btnArray[3].handle = (row) => {
  router.push({
    path: '/modules/train/examine/query', query: {
      batchNum: row.batchNum,
      studentNum: row.studentNum,
      payFlag: row.payFlag,
      id: row.id,
    }
  })
}
// 删除
tableItem.btnArray[5].handle = (row) => {
  proxy.$modal.confirm("确定删除" + row.batchNum || '').then(() => {
    batchDelApi({ idList: [row.id] }).then(res => {
      ElMessage.success('操作成功'); tableItem.pageInfo.paging()
    })
  })
}


// =======处理 缴费 功能========
//#region 

//缴费
tableItem.btnArray[2].handle = (row) => {
  paymentDialog.show()
  payInfo.id = row.id;
}

//表单校验规则
const paymentRules = reactive({
  payPrice: [
    { required: true, message: '请输入缴费金额', trigger: 'blur' },
  ],
  payDate: [
    { required: true, message: '请先择日期', trigger: 'blur' },
  ],
})

//payment 的 http数据包
const payInfo = reactive({
  id: "",
  payPrice: "",
  payDate: "",
  payProofUrl: ""
})

const paymentForm = ref('')
const paymentDialog = newDialog(paymentForm, payInfo, paymentRules);

//缴费凭证上传成功的回调函数
function handleUploadSuccess(response) {
  payInfo.payProofUrl = response.url
  ElMessage({ message: "上传成功", type: 'success' })
}

//缴费凭证上传失败的回调函数
function handleUploadError(Error) {
  ElMessage.error("上传失败")
}

//表单确认提交
paymentDialog.doConfirm = (request) => {
  paymentApi(request).then((result) => {
    let response = result
    paymentDialog.close()
    ElMessage({ message: response.msg, type: "success" })
    tableItem.pageInfo.paging()
  });
}
//#endregion
</script>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    text-align: center;
}</style>